import { useUserStore } from '@/stores/user'
import { useAuthStore } from '@/stores/auth'
import { isWechat } from '@/utils'

export function setupRouterGuards(router) {
  router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()
    const authStore = useAuthStore()

    // 检查是否需要登录
    if (to.meta.requiresAuth) {
      // 在微信环境中且没有授权
      if (isWechat() && !authStore.wxUserInfo) {
        authStore.getWxAuth()
        return
      }

      // 没有登录则跳转到登录页
      if (!userStore.token) {
        next({
          path: '/doctor/login',
          query: { redirect: to.fullPath }
        })
        return
      }
    }

    next()
  })

  // 路由错误处理
  router.onError((error) => {
    console.error('路由错误:', error)
  })
} 